package com.github.template;

import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName GeneratorServices
 * @Description TODO
 * @Author shuang669539827@163.com
 * @Date2019/6/28 16:43
 * @Version v1.0
 **/
public class GeneratorService {

    private String dir;

    private String names;


    /**
     * 获取用户配置的模板
     * @return
     */
    public List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        if (names!=null && names.length()>0){
            String[] split = names.split(",");
            templates = Arrays.stream(split).collect(Collectors.toList());
        }
        return templates;
    }


    /**
     * 生成代码
     */
    public byte[] genCode(Map<String, Object> params) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //写入zip
        for (String templateName : getTemplates()) {
            //自动根据用户引入的模板引擎库的jar来自动选择使用的引擎
            //TemplateConfig为模板引擎的选项，可选内容有字符编码、模板路径、模板加载方式等，默认通过模板字符串渲染
            TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig(dir, TemplateConfig.ResourceMode.CLASSPATH));
            //假设我们引入的是Beetl引擎，则：
            Template template = engine.getTemplate(dir+ File.separator+templateName);
            //Dict本质上为Map，此处可用Map
            String result = template.render(params);
            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry("index.html"));
                IOUtils.write(result, zip, "UTF-8");
                zip.closeEntry();
            } catch (IOException e) {
                throw new Exception("渲染模板失败，文件名：", e);
            }
        }

        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();

    }


    public void setDir(String dir) {
        this.dir = dir;
    }

    public void setNames(String names) {
        this.names = names;
    }
}
